package com.dartfar.menu.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.action.BaseAction;
import com.dartfar.base.model.T_User;
import com.dartfar.base.service.AuthorityService;
import com.dartfar.base.vo.FunctionVo;
import com.dartfar.base.vo.MenuTreeGridVo;
import com.dartfar.base.vo.TreeVo;
import com.dartfar.menu.model.Menu;
import com.dartfar.menu.service.MenuService;
import com.dartfar.menu.vo.MenuVo;
import com.dartfar.util.EntityUtils;
import com.dartfar.util.ListUtil;

/**
 * 菜单Action对象
 * @author 王琦
 */
@Component("menuAction")
@Scope("prototype")
public class MenuAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Service对象
	 */
	private MenuService menuService;
	private AuthorityService authorityService;
	

	/**
	 * 页面传参
	 */
	private MenuVo menuVo;
	private List<MenuTreeGridVo> menuTreeGridVos;
	private String name;
	private String target;
	private int menuOrder;
	private String iconCls;
	private int parentId;
	private String des;
	private int id;
	private int menuId;
	private int mainId;
	private String code;
	
	private List<FunctionVo> functions;
	
	/**
	 * 页面跳转
	 */
	public String show(){
		
		return "show";
	}
	
	/**
	 * 增加菜单
	 */
	public String add(){	
		menuVo = new MenuVo();
		menuVo.setName(name);
		menuVo.setTarget(target);
		menuVo.setMenuOrder(menuOrder);
		if(iconCls.length() == 0){
			iconCls = "icon-app";
		}
		menuVo.setIconCls(iconCls);
		menuVo.setCode(code);
		menuVo.setParentId(parentId);
		menuVo.setMainId(mainId);
		menuVo.setDes(des);
		menuVo.setLeaf(true);
		int menuId = menuService.add(menuVo);
		Menu menu = menuService.get(menuId);
		List<Menu> menus = new ArrayList<Menu>();
		menus.add(menu);
		//menuList对象转TreeGridVoList对象
		menuTreeGridVos = menu2TreeGrids(menus);
		return SUCCESS;
	}
	
	/**
	 * 编辑菜单
	 */
	public String edit(){
		Menu menu = menuService.get(id);
		menuVo = new MenuVo();   
		menuVo.setId(id);
		menuVo.setName(name);
		menuVo.setTarget(target);
		menuVo.setCode(code);
		menuVo.setMenuOrder(menuOrder);
		menuVo.setIconCls(iconCls);
		menuVo.setParentId(parentId);
		menuVo.setMainId(mainId);
		menuVo.setDes(des);
		menuVo.setLeaf(menu.isLeaf());
		menuService.modify(menuVo);
		return SUCCESS;
	}
	
	/**
	 * 删除菜单
	 */
	public String delete(){
		menuService.delete(id);
		return SUCCESS;
	}
	
	/**
	 * 获取主菜单
	 */
	public String loadMainMenusData(){
		List<Menu> menus = menuService.getMainMenuLsit();
		List<MenuVo> menuVos = new ArrayList<MenuVo>();
		
		MenuVo menuVo = new MenuVo();
		menuVo.setId(0);
		menuVo.setName("无");
		menuVos.add(menuVo);
		for(Iterator<Menu> i = menus.iterator();i.hasNext();){
			Menu menu = i.next();
			menuVo = new MenuVo();
			menuVo.setId(menu.getId());
			menuVo.setName(menu.getName());
			menuVos.add(menuVo);
		}
		
		String jsonResult = JSONArray.fromObject(menuVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取父菜单
	 */
	public String loadParentMenusData(){
		List<MenuVo> menuVos = new ArrayList<MenuVo>();
		MenuVo menuVo = new MenuVo();
		menuVo.setId(0);
		menuVo.setName("无");
		menuVos.add(menuVo);
		if(mainId != 0){
			List<Menu> menus = menuService.getSubMenuList(mainId);
			
			for(Iterator<Menu> i = menus.iterator();i.hasNext();){
				Menu menu = i.next();
				menuVo = new MenuVo();
				//role对象克隆roleVo
				try{
					BeanUtils.copyProperties(menuVo, menu);
				}catch(Exception ex){
					ex.printStackTrace();
				}	
				menuVos.add(menuVo);
			}
		}
		
		String jsonResult = JSONArray.fromObject(menuVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 根据主菜单ID获取功能菜单列表 
	 * @return
	 */
	public String loadSubMenuTree(){
		List<TreeVo> newTreeVos = new ArrayList<TreeVo>();	
		TreeVo treeVo = new TreeVo();
		treeVo.setId(0+"");
		treeVo.setText("无");
		newTreeVos.add(treeVo);
		if(mainId != 0){
			List<Menu> subMenus = menuService.getSubMenuList(mainId);
			//把SubMenuList转化TreeVo对象
			List<TreeVo> oldTreeVos = subMenus2Trees(subMenus, 0, mainId);
			//重写TreeVos
			for(Iterator<TreeVo> i = oldTreeVos.iterator();i.hasNext();){
				treeVo = i.next();
				newTreeVos.add(treeVo);
			}
		}
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(newTreeVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 根据主菜单ID获取功能菜单列表    联动
	 * 递归树SubMenuList转为TreeVoList对象
	 * @param  subMenus 子菜单列表
	 * @param parentId 父菜单ID
	 * @param mainId 主菜单ID
	 * @return
	 */
	public List<TreeVo> subMenus2Trees(List<Menu> subMenus, int parentId, int mainId){	
		List<TreeVo> treeVos = new ArrayList<TreeVo>();		
		for(Iterator<Menu> i = subMenus.iterator();i.hasNext();){
			Menu subMenu = i.next();
			int subMenuParentId = 0;
			if(subMenu.getParentMenu() != null){
				subMenuParentId = subMenu.getParentMenu().getId();
			}
			
			if(parentId == subMenuParentId){
				TreeVo treeVo = new TreeVo();
				treeVo.setId(subMenu.getId()+"");
				treeVo.setText(subMenu.getName());
				treeVo.setCode(subMenu.getCode());
				treeVo.setIconCls(subMenu.getIconCls());
				if(!subMenu.isLeaf()){
					//树结点为关闭
					treeVo.setState("open");
					//递归下级子结点
					List<TreeVo> treeVos1 = subMenus2Trees(subMenus, subMenu.getId(), mainId);
					treeVo.setChildren(treeVos1);
				}
				treeVos.add(treeVo);
			}
		}
		return treeVos;
	}
	
	
	
	/**
	 * 获取菜单管理的主菜单列表
	 * @return 主菜单的Json字符串
	 */
	public String loadMenuTreeGrid(){
	
		
		//主菜单VO对象
		List<MenuTreeGridVo> treeDepartsVos = new ArrayList<MenuTreeGridVo>();
		
		try{
			
		
		List<Menu> menus = menuService.getMainMenuLsit();
		for (Iterator<Menu> m = menus.iterator(); m.hasNext();) {
			Menu menu = m.next();
			MenuTreeGridVo treeMainVo = new MenuTreeGridVo();
			treeMainVo.setId(menu.getId());
			treeMainVo.setName(menu.getName());
			treeMainVo.setCode(menu.getCode());
			treeMainVo.setIconCls(menu.getIconCls());
			treeMainVo.setTarget(menu.getTarget());
			treeMainVo.setMenuOrder(menu.getMenuOrder());
			treeMainVo.setDes(menu.getDes());
			if(EntityUtils.isNotNull(menu.getMainMenu())){
				treeMainVo.setMainId(menu.getMainMenu().getId());
			}
			if(EntityUtils.isNotNull(menu.getParentMenu())){
				treeMainVo.setParentId(menu.getParentMenu().getId());
			}
			
			//如果是子节点
			if(!menu.isLeaf()){
//				treeMainMenuVo.setState("open");
				//List<Department> subDeparts = departService.getListByParentId(depart.getId());
				List<Menu> farMenus = menuService.getListByParentId(0, menu.getId());
				List<MenuTreeGridVo> treeSubDepartVos = menuTree2TreeGrids(farMenus, menu.getId());
				treeMainVo.setChildren(treeSubDepartVos);
			}
			treeDepartsVos.add(treeMainVo);
		}
		
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		String jsonResult = JSONArray.fromObject(treeDepartsVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 部门管理 部门树 遍历子部门
	 * @return TreeVo的Json字符串
	 */
	public List<MenuTreeGridVo> menuTree2TreeGrids(List<Menu> menus, int menuId){
		List<MenuTreeGridVo> treeGridVos = new ArrayList<MenuTreeGridVo>();
		for(Iterator<Menu> i = menus.iterator();i.hasNext();){
			Menu menu = i.next();
			MenuTreeGridVo treeGridVo = new MenuTreeGridVo();
			treeGridVo.setId(menu.getId());
			treeGridVo.setName(menu.getName());
			treeGridVo.setCode(menu.getCode());
			treeGridVo.setIconCls(menu.getIconCls());
			treeGridVo.setTarget(menu.getTarget());
			treeGridVo.setMenuOrder(menu.getMenuOrder());
			treeGridVo.setDes(menu.getDes());
			if(EntityUtils.isNotNull(menu.getMainMenu())){
				treeGridVo.setMainId(menu.getMainMenu().getId());
			}
			if(EntityUtils.isNotNull(menu.getParentMenu())){
				treeGridVo.setParentId(menu.getParentMenu().getId());
			}
			//如果不是叶子结点，结点关闭
			if(!menu.isLeaf()){
				treeGridVo.setState("closed");
				List<Menu> farMenus = menuService.getListByParentId(0, menu.getId());
				List<MenuTreeGridVo> treeSubDepartVos = menuTree2TreeGrids(farMenus, menu.getId());
				treeGridVo.setChildren(treeSubDepartVos);
			}
			treeGridVos.add(treeGridVo);
		}
		return treeGridVos;
	}
	
	
	
	/**
	 * 获取菜单管理的主菜单列表
	 * @return 主菜单的Json字符串
	 */
	public String loadTreeGrid(){
		List<Menu> menus = menuService.getMainMenuLsit();
		List<MenuTreeGridVo> menuTreeGridVos = menu2TreeGrids(menus);
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(menuTreeGridVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}	
	
	/**
	 * 获取父菜单ID下功能的根节点
	 * @return 根节点的Json字符串
	 */
	public String loadChildrenTreeGrid(){
		List<Menu> menus = menuService.getListByParentId(parentId, mainId);
		//递归下级子结点
		List<MenuTreeGridVo> menuTreeGridVos = menu2TreeGrids(menus);
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(menuTreeGridVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * MenuList对象转MenuTreeGridVoList对象
	 * @param Menus 菜单列表
	 * @return 树列表
	 */
	public List<MenuTreeGridVo> menu2TreeGrids(List<Menu> menus){		
		List<MenuTreeGridVo> menuTreeGridVos = new ArrayList<MenuTreeGridVo>();
		for(Iterator<Menu> i = menus.iterator();i.hasNext();){
			Menu menu = i.next();
			MenuTreeGridVo menuTreeGridVo = new MenuTreeGridVo();
			menuTreeGridVo.setId(menu.getId());

			if(menu.getMainMenu() == null){
				menuTreeGridVo.setMainId(0);
			}else{
				menuTreeGridVo.setMainId(menu.getMainMenu().getId());
			}
			
			if(menu.getParentMenu() == null){
				menuTreeGridVo.setParentId(0);
			}else{
				menuTreeGridVo.setParentId(menu.getParentMenu().getId());
			}
			menuTreeGridVo.setCode(menu.getCode());
			menuTreeGridVo.setName(menu.getName());
			menuTreeGridVo.setTarget(menu.getTarget());
			menuTreeGridVo.setMenuOrder(menu.getMenuOrder());
			menuTreeGridVo.setDes(menu.getDes());
			menuTreeGridVo.setIconCls(menu.getIconCls());
			menuTreeGridVo.setSubMenu(menu.isLeaf());
			//如果不是子节点，则设置TreeGrid有下级节点，并且设置为关闭状态
			if(!menu.isLeaf()){
				menuTreeGridVo.setState("closed");
			}
			menuTreeGridVos.add(menuTreeGridVo);
		}
		return menuTreeGridVos;
	}
	
	
	/**
	 * 主页菜单遍历 权限用
	 * @return 根节点的Json字符串
	 */
	public String loadTreeDataByMenuId(){
		List<Menu> menus = new ArrayList<Menu>();
		List<Menu> subMenus = (List<Menu>) session.get("subMenus");
		//删除重复菜单
		menus = new ListUtil<Menu>().removeRepeat(subMenus, menus);
		//功能排序
		Collections.sort(menus, new Comparator<Menu>() {  
	          public int compare(Menu m1, Menu m2) {  
	            return m1.getMenuOrder() - m2.getMenuOrder() ;   
	          }  
	       });
		
		List<TreeVo> treeVos = menus2Trees(menus, 0, menuId);
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(treeVos).toString();
		System.out.println("jsonResult: " + jsonResult);
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}

		return null;
	}
	
	
	/**
	 * 子菜单树递归
	 * @param functions 功能列表
	 * @param parentId 父结点ID
	 * @param menuId 主菜单ID
	 * @return
	 */
	public List<TreeVo> menus2Trees(List<Menu> menus, int parentId,
			int menuId) {
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		for (Iterator<Menu> i = menus.iterator(); i.hasNext();) {
			Menu menu = i.next();
			int menuParentId = 0;

			if (menu.getParentMenu() != null) {
				menuParentId = menu.getParentMenu().getId();
			}

			if (parentId == menuParentId && menu.getMainMenu().getId() == menuId) {
			//if(menuParentId == menuId){
				TreeVo treeVo = new TreeVo();
				treeVo.setId(menu.getId()+"");
				treeVo.setText(menu.getName());
				treeVo.setCode(menu.getCode());
				treeVo.setIconCls(menu.getIconCls());
				//如果不是叶子节点，树结点打开
				if (!menu.isLeaf()) {
					treeVo.setState("closed");
					//递归下级结点
					List<TreeVo> subTreeVos = menus2Trees(menus, menu.getId(), menuId);
					treeVo.setChildren(subTreeVos);
				}
				treeVos.add(treeVo);
			}
		}
		return treeVos;
	}


	/**
	 * 根据ID获取功能
	 */
	public String get(){
		Menu menu = menuService.get(id);
		menuVo = new MenuVo();
		//从function中对象克隆到functionVo
		try{
			BeanUtils.copyProperties(menuVo, menu);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * Spring注入Service
	 */
	
	@Resource
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}
	
	@Resource
	public void setAuthorityService(AuthorityService authorityService) {
		this.authorityService = authorityService;
	}


	public int getParentId() {
		return parentId;
	}

	public void setParentId(int parentId) {
		this.parentId = parentId;
	}

	public MenuVo getMenuVo() {
		return menuVo;
	}

	public void setMenuVo(MenuVo menuVo) {
		this.menuVo = menuVo;
	}

	public List<MenuTreeGridVo> getMenuTreeGridVos() {
		return menuTreeGridVos;
	}

	public void setMenuTreeGridVos(List<MenuTreeGridVo> menuTreeGridVos) {
		this.menuTreeGridVos = menuTreeGridVos;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public int getMenuOrder() {
		return menuOrder;
	}

	public void setMenuOrder(int menuOrder) {
		this.menuOrder = menuOrder;
	}

	public String getIconCls() {
		return iconCls;
	}

	public void setIconCls(String iconCls) {
		this.iconCls = iconCls;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getMenuId() {
		return menuId;
	}

	public void setMenuId(int menuId) {
		this.menuId = menuId;
	}

	public int getMainId() {
		return mainId;
	}

	public void setMainId(int mainId) {
		this.mainId = mainId;
	}

	public List<FunctionVo> getFunctions() {
		return functions;
	}

	public void setFunctions(List<FunctionVo> functions) {
		this.functions = functions;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	

}
